<template>
  <div class="edit-phpto">
    <img :src="img" alt="" ref="img" />
    <div class="operation">
      <van-button type="default" size="small" @click="$emit('cancel')">
        取消</van-button
      >
      <van-button type="default" size="small" @click="accomplish()"
        >完成</van-button
      >
    </div>
  </div>
</template>

<script>
// 引入裁剪图片的库与样式
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { editPhpto } from '@/api/my/userinfo.js'
export default {
  data () {
    return {
      cropper: null
    }
  },
  props: ['img'],
  created () {},
  mounted () {
    this.tailorPhoto()
  },
  methods: {
    tailorPhoto () {
      const image = this.$refs.img
      this.cropper = new Cropper(image, {
        viewMode: 1,
        dragMode: 'move',
        aspectRatio: 1,
        autoCropArea: 1,
        cropBoxMovable: true,
        cropBoxResizable: true,
        background: false,
        movable: false
      })
    },
    // 完成裁剪
    accomplish () {
      // 因为改头像有延迟优化用户体验
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        loadingType: 'spinner',
        message: '保存中'
      })
      try {
        console.log(this.cropper.getCroppedCanvas())
        this.cropper.getCroppedCanvas().toBlob(async (blob) => {
          const formData = new FormData()
          // 往表单对象后追加图片对象
          formData.append('photo', blob)
          const { data } = await editPhpto(formData)
          // 关闭弹出层
          this.$emit('cancel')
          // 改变头像
          this.$emit('changePhpto', data.data.photo)
          this.$toast('修改成功')
        })
      } catch (error) {
        console.log(error)
        this.$toast('修改失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.edit-phpto {
  height: 100%;
  background: #000;
  .operation {
    position: absolute;
    bottom: -30px;
    width: 100%;
    height: 120px;
    display: flex;
    justify-content: space-around;
  }
  img {
    display: block;
    max-width: 100%;
  }
}
</style>
